package org.zjt.agent.runtime;

import org.zjt.agent.ClassFileTransformerLoader;
import org.zjt.agent.runtime.reloader.ClassByteReloader;
import org.zjt.agent.runtime.reloader.ClassFileReloader;
import org.zjt.agent.runtime.reloader.ClassReloader;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-10-24 2:23 PM
 * @see
 */
public class RuntimeAgent {

    private static final Logger LOGGER = Logger.getLogger(RuntimeAgent.class.getName());
    /**
     * 运行时候利用attach加载的
     * @param agentOps
     * @param inst
     */
    public static void agentmain(String agentOps, Instrumentation inst){
        LOGGER.info("=========RuntimeAgent agentmain方法执行========");

        ClassByteReloader classByteReloader = new ClassByteReloader(inst);
        ClassFileReloader classFileReloader = new ClassFileReloader(inst);
        List<ClassReloader> classReloaders = Arrays.asList(classByteReloader, classFileReloader);
        ClassFileTransformer classFileTransformer = new RuntimeClassTransformer(ClassFileTransformerLoader.load(), classReloaders);
        inst.addTransformer(classFileTransformer, Boolean.TRUE);

        classReloaders.forEach(item -> {
            try {
                item.startup();
            } catch (UnmodifiableClassException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
